var express = require('express');//加载express框架
var http = require('http');//加载http模块
var path = require('path');//加载path模块，获取文件名模块
var MongoStore = require('connect-mongo')(express);
var settings = require('./settings');
var flash = require('connect-flash');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes');//加载routes下的index.js
// var users = require('./routes/user');//加载routes下的user.js

var app = express();

// view engine setup*设置模板引擎存储的位置和使用的模板引擎类型
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(flash());

app.use(favicon());
app.use(logger('dev'));
app.use(express.bodyParser({keepExtensions:true,uploadDir: './public/images'}));//参考资料版本express写法
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded());//新版express写法，当前两行可替代app.use(express.bodyParser());
app.use(cookieParser());
app.use(express.session({
    secret: settings.cookieSecret,
    key: settings.db,//cookie name
    cookie: {maxAge: 1000*60*60*24*30},//30 days
    store: new MongoStore({
        //db: settings.db
        url:'mongodb://localhost/blog'
    })
}));
app.use(express.static(path.join(__dirname, 'public')));//connect内建的中间件，将根目录下的public文件夹设置为存放为images、css、js等静态文件夹的目录
app.use(app.router);//调用路由解析规则

// app.get('/', routes.index);//路由控制器，如果用户访问/（主页），则由router.index来处理，路由到router/index.js的内容
// // router/index.js的内容如下：
exports.index = function(req, res){
  res.render('index', { title: 'Express' });
};
// app.get('/users', users.list);


/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
// *配置开发环境下的错误处理
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;
routes(app);//删除var user = require('./router/user')后增加的内容
